const router = require('koa-router')()
const phantom = require('phantom');
const cheerio = require('cheerio');
const xlsx = require('node-xlsx');
const fs = require('fs');

var data1 = [
    /*
    ["0986AB1367", "148"],
    ["0986AB1323", "158"],
    ["0986AB1670", "158"],
    ["0986AB1341", "168"],
    ["0986AB3895", "148"],
    ["0986AB1166", "148"],
    ["0986AB3771", "148"],
    ["0986AB1155", "158"],
    ["0986AB1156", "158"],
    ["0986AB1174", "168"],
    ["0986AB1663", "158"],
    ["0986AB3776", "168"],
    ["0986AB1148", "198"],
    ["0986AB1151", "198"],
    ["0986AB1177", "218"],
    ["0986AB1188", "168"],
    ["0986AB2592", "168"],
    ["0986AB1374", "218"],
    ["0986AB1692", "218"],
    ["0986AB1191", "258"],
    ["0986AB2805", "258"],
    ["0986AB2823", "258"],
    ["0986T11022", "258"],
    ["0986AB1598", "168"],
    ["0986AB1690", "168"],
    ["0986AB1369", "198"],
    ["0986AB1327", "218"],
    ["0986AB1328", "218"],
    ["0986AB1594", "218"],
    ["0986AB1612", "218"],
    ["0986AB1662", "218"],
    ["0986AB3757", "148"],
    ["0986AB2808", "168"],
    ["0986AB1178", "198"],
    ["0986AB1147", "248"],
    ["0986AB1185", "218"],
    ["0986AB1189", "218"],
    ["0986AB1164", "258"],
    ["0986AB1195", "168"],
    ["0986AB1149", "218"],
    ["0986AB2640", "218"],
    ["0986AB1590", "258"],
    ["0986AB2641", "258"],
    ["0986AB1190", "268"],
    ["0986AB1322", "288"],
    ["0986AB9413", "268"],
    ["0986503001", "138"],
    ["0986AB2902", "168"],
    ["0986AB3909", "168"],
    ["0986AB1649", "288"],
    ["0986AB1186", "218"],
    ["0986AB1326", "218"],
    ["0986AB1152", "258"],
    ["0986AB9409", "288"],
    ["0986AB1617", "168"],
    ["0986AB1182", "218"],
    ["0986AB1596", "218"],
    ["0986AB2904", "218"],
    ["0986AB1170", "218"],
    ["0986AB1153", "198"],
    ["0986AB1169", "198"],
    ["0986AB1704", "198"],
    ["0986AB3808", "168"],
    ["0986AB1184", "218"],
    ["0986AB1194", "218"],
    ["0986AB1634", "198"],
    ["0986AB1160", "148"],
    ["0986AB2628", "218"],
    ["0986AB1154", "168"],
    ["0986AB1173", "218"],
    ["0986AB1173", "218"],
    ["0986AB1368", "218"],
    ["0986AB1619", "218"],
    ["0986AB1187", "218"],
    ["0986AB1613", "198"],
    ["0986AB1620", "218"],
    ["0986AB9471", "218"],
    ["0986AB1183", "218"],
    ["0986AB2912", "168"]
    */
    ["7CD_U","25"],
    ["新风翼","43"],
    ["AERO_U","72"],
    ["8CT_4in1","79"],
    ["8CT_6in1","89"],
    ["3397118925","168"],
    ["3397118933","128"]
]
var data2 = [
    /*
    { url: "zhenxicp.tmall.com", title: "震曦车品专营店" },
    { url: "lefengqcyp.tmall.com", title: "勒丰汽车用品专营店" },
    { url: "yixinqcyp.tmall.com", title: "异新汽车用品专营店" },
    { url: "boschyj.tmall.com", title: "bosch博世佑杰专卖店" },
    { url: "guangbingcp.tmall.com", title: "光兵车品专营店" }
    */
    //https://boschqcpj.tmall.com/
    { url: "boschqcpj.tmall.com", title: "博世旗舰店" }
]

var seachUrl = "https://{1}/?q={0}&type=p&search=y";
router.get('/', async (ctx, next) => {
    var saveData = [
        ["店铺名称", "货号", "建议价格", "商品名称", "实际价格", "状态"]
    ];

    var startTime = (new Date().getTime()) / 1000;
    for (var i = 0; i < data1.length; i++) {
        var url1 = seachUrl.replace('{0}', data1[i][0]);
        for (var j = 0; j < data2.length; j++) {
            url = url1.replace('{1}', data2[j].url);
            console.log("店铺:" + data2[j].title);
            console.log("货号:" + data1[i][0]);
            console.log("建议价格:" + data1[i][1]);
            var saveData1 = [];
            saveData1.push(data2[j].title, data1[i][0], data1[i][1])
            var saveData2 = await digui(url, data1[i][1]);
            for (var k = 0; k < saveData2.length; k++) {
                saveData1.push(saveData2[k]);
            }
            saveData.push(saveData1);
            console.log("***************" + i);

        }
    }
    var endTime = (new Date().getTime()) / 1000;
    ctx.body = "完成";
    console.log("========" + (endTime - startTime) + "=========");
    var buffer = xlsx.build([
        { "name": "Group", "data": saveData }
    ]);
    var date = new Date();
    var str = date.toDateString();
    fs.writeFileSync("save/" + str + ".csv", buffer, 'binary');
})

async function pachong(url) {
    const instance = await phantom.create();
    const page = await instance.createPage();
    await page.on('onResourceRequested', function (requestData) {
        //console.info('Requesting', requestData.url);
    });
    const status = await page.open(url);
    const content = await page.property('content');
    await instance.exit();
    return content;
}
async function digui(url, jyPrice) {
    var data = [];
    var content = await pachong(url);
    var $ = cheerio.load(content);
    var itemA = $('.item-name');
    if (itemA.length > 0) {
        var pagination = $('.pagination');
        if (pagination.length == 0) {
            console.log("未上架");
            data.push("未上架");
            return data;
        }
        else {
            var itemHref = "https:" + itemA[0].attribs.href;
            console.log(itemHref);
            content = await pachong(itemHref);
            $ = cheerio.load(content);
            var title = $('.tb-detail-hd')[0].children[1].children[0].data.trim();
            var price = $('.tm-price')[0].firstChild.data.trim();
            console.log("商品名称:" + title);
            console.log("实际价格:" + price);
            data.push(title);
            data.push(price);
            var pa = jyPrice - price;
            if (pa == 0) {
                console.log("状态:正常");
                data.push("正常");
            }
            else if (pa > 0) {
                console.log("状态:偏低");
                data.push("偏低");
            }
            else if (pa < 0) {
                console.log("状态:偏高");
                data.push("偏高")
            }
            return data;
        }
    }
    else {
        //console.log("抓取失败，重试");
        return (await digui(url, jyPrice));
    }
}
module.exports = router